﻿using GMS.NET.Application.Service.System.MqttNet;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using MQTTnet.AspNetCore;

namespace GMS.NET.Application.Service.System.Extensions
{
    public static class IotHubMqttServerExtensions
    {
        public static void AddIotHubMqttServer(this IServiceCollection services,
            Action<AspNetMqttServerOptionsBuilder> configure)
        {
            services.AddHostedMqttServerWithServices(builder =>
            {
                configure(builder);
            });
            services.AddMqttConnectionHandler();
            services.AddConnections();
        }



        public static void UseIotHubMqttServer(this IApplicationBuilder app)
        {
            app.UseMqttServer(mqttServer =>
            {
                app.ApplicationServices.GetRequiredService<IIotHubMqttServer>()
                .ConfigureMqttServer(mqttServer);
            });


            app.UseEndpoints(endpoints =>
            {
                endpoints.MapConnectionHandler<MqttConnectionHandler>("/mqtt",//端口/mqtt
                    httpConnectionDispatcherOptions => httpConnectionDispatcherOptions.WebSockets.SubProtocolSelector =
                    protocolList => protocolList.FirstOrDefault() ?? string.Empty);
            });

        }
    }
}
